const { getUserAddresses } = require('../../../services/address/address');
const addressManager = require('../../../model/address');
const { getUserData } = require('../../../model/user');
const { submitOrder, updateOrderStatus } = require('../../../services/order/orderConfirm');
const userModel = require('../../../model/user');
 
Page({
  data: {
    wine: {}, // 商品信息
    quantity: 1, // 商品数量
    addresses: [],
    selectedAddress: {}, // 已选择的地址
    isRemarkPopupVisible: false,
    remarks: '', // 用户备注
    remarksDisplay: '',
    totalPrice: '0.00',
    productPrice: '0.00'
  },

  onLoad() {
    const app = getApp();
    const orderData = app.globalData.orderData;
    const user = userModel.getUserData();
    if (orderData) {
      const wine = orderData.product;
      const quantity = orderData.quantity || 1;
      const price = (user.info.role === 'GUEST') ? wine.price : wine.memberPrice;

      this.setData({ 
        wine, 
        quantity,
        productPrice: price.toFixed(2),
        totalPrice: (price * quantity).toFixed(2), 
      });
    } else {
      console.error('Order data not found in globalData');
    }
  },

  onShow() {
    this.loadAddresses();
  },

  onQuantityChange(newQuantity) {
    this.setData({ 
      quantity: newQuantity,
      totalPrice: (this.data.wine.price * newQuantity).toFixed(2), // 更新总价
    });
  },

  async loadAddresses() {
    try {
      const serverAddresses = await getUserAddresses();
      const localAddresses = addressManager.getAllAddresses();

      // 合并本地和服务器地址列表
      const mergedAddresses = serverAddresses.map((serverAddress) => {
        const localAddress = localAddresses[serverAddress.id];
        return {
          ...serverAddress,
          isDefault: localAddress?.isDefault || false, // 优先使用本地的 isDefault 信息
        };
      });

      // 确定选中的地址
      const selectedAddressId = addressManager.getSelectedAddressId();
      let selectedAddress = {};

      if (mergedAddresses.length > 0) {
        if (selectedAddressId) {
          selectedAddress = mergedAddresses.find((addr) => addr.id === selectedAddressId) || {};
        }

        if (!selectedAddress.id) {
          const defaultAddresses = mergedAddresses.filter((addr) => addr.isDefault);
          selectedAddress = defaultAddresses.length > 0 ? defaultAddresses[0] : mergedAddresses[0];
        }
      }

      this.setData({
        addresses: mergedAddresses,
        selectedAddress: selectedAddress || {},
      });
    } catch (error) {
      console.error('加载地址失败', error);
    }
  },

  onBack() {
    wx.navigateBack();
  },

  onSelectAddress(event) {
    const { address } = event.detail;
    this.setData({ selectedAddress: address });
  },

  onEditRemarks() {
    this.setData({ isRemarkPopupVisible: true });
  },
  
  onConfirmRemarks(event) {
    const { remarks } = event.detail;
    this.setData({
      remarks,
      remarksDisplay: remarks.length > 15 ? remarks.substring(0, 15) + '...' : (remarks || ''),
      isRemarkPopupVisible: false,
    });
  },

  onCancelRemarks() {
    this.setData({ isRemarkPopupVisible: false });
  },

  async onSubmitOrder() {
    if (!this.data.selectedAddress || Object.keys(this.data.selectedAddress).length === 0) {
      // 地址未填写，提示选择地址
      wx.showToast({
        title: '请先选择地址',
        icon: 'none',
      });
      return;
    }

    // 地址已填写，正常提交订单逻辑
    wx.showLoading({ title: '提交中...' });
    const user = getUserData(); // 获取用户信息
    const wxPayArgs = await submitOrder({
        userId: user.info.id,
        totalPrice: parseFloat(this.data.totalPrice),
        shippingAddressId: this.data.selectedAddress.id,
        paymentMethod: "wechatPay",
        parentId: user.info.parentId,
        openid: user.info.openid,
        wineId: this.data.wine.id,
        wineName: this.data.wine.name,
        wineNum: this.data.quantity,
        remarks: this.data.remarksDisplay
    })
    if (!wxPayArgs) {
        return;
    }
    const { orderId, channelOrderId, ...payArgs } = wxPayArgs;
    wx.requestPayment({
        ...payArgs,
        success (res) { 
            // 显示支付成功页面
            wx.showToast({
                title: '订单提交成功',
                icon: 'success',
            });
            updateOrderStatus(orderId, "PAYED")
            wx.navigateTo({ url: '/pages/order/pay-result/index' });
        },
        fail (res) {
            console.error(res)
            // cannel
            if (res && res.errMsg === "requestPayment:fail cancel") {
                wx.showToast({
                    title: '取消支付',
                    icon: 'error'
                });
                updateOrderStatus(orderId, "CANCELED");
            } else {
                wx.showToast({
                    title: '支付失败',
                    icon: 'error'
                });
                updateOrderStatus(orderId, "FAIL");
            }
         },
         complete() {
            wx.hideLoading();
         }
      })
  },
});
